<?php

namespace App\Http\Controllers\Admin;

use App\CodeResponse;
use App\Models\GoodsCategory;
use App\Services\GoodsBrandService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;

class GoodsCategoryController extends AdminController
{
    //保存
    public function save(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'id' => 'integer|digits_between:1,20|min:1',
            'name' => 'required|string',
            'pid' => 'required|integer',
            'status' => 'required|integer',

        ]);
        if ($validator->fails()) {
            return $this->fail(CodeResponse::PARAM_ILLEGAL);
        }
        $putData = $request->except(['_method', '_token']);
        $id = $request->input('id');
        $flight = GoodsCategory::updateOrCreate(
            ['id' => $id],
            $putData
        );
        return $this->success($flight->id);
    }
    /**
     * 获取列表
     * @return
     */
    //根据父id获取列表
    public function plist(Request $request){
        $pid = $request->input('pid',0);
        $goodsCategoryAll = (new GoodsCategory())->getPList($pid);
        return $this->success(array_values($goodsCategoryAll));
    }
    //列表
    public function listTree(Request $request){
        // 读取出所有的分类
        $goodsCategoryAll = (new GoodsCategory())->getAllList();
        return $this->success($goodsCategoryAll);
    }
    //删除
    public function delete(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'id' => 'required|integer',
        ]);
        if ($validator->fails()) {
            return $this->fail(CodeResponse::PARAM_ILLEGAL);
        }
        $goodsCategory = new GoodsCategory();
        $arr = $goodsCategory->getSubTreeIdArr($request->id);
        array_push($arr,$request->id);
        $goodsCategory->destroy($arr);
        return $this->success();
    }
}
